using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ScrollController : MonoBehaviour
{
    Message message;
    public InputField inputText;
    public RectTransform content;
    public GameObject newText;

    //一个text方块的高和数量
    public int textHeight = 30;
    //view的高
    public int viewPortH;
    
    //用于Content的下标位置
    private int oldMinIndex = -1;//Content一开始为0
    private int oldMaxIndex = -1;
    
    public Dictionary<int, GameObject> textDictionary = new Dictionary<int, GameObject>();
    //对象池
    List<GameObject> pool=new List<GameObject>();
    
    public Message Message
    {
        set { message = value;}
    }
    

    // Update is called once per frame
    void Update()
    {
        content.sizeDelta=new Vector2(0,message.getMessage.Count*textHeight);
        TextControl();
    }      
    

    void TextControl()
    {
        int minIndex = ( int ) (content.anchoredPosition.y/textHeight);
        int maxIndex = ( int ) ((content.anchoredPosition.y+viewPortH)/textHeight);

        for (int i = oldMinIndex; i < minIndex; i++)
        {
            if (textDictionary.ContainsKey(i))
            {
                textDictionary[i].SetActive(false);
                pool.Add(textDictionary[i]);
                textDictionary.Remove(i);
            }
        }
        
        for (int i = maxIndex+1; i <= oldMaxIndex; i++)
        {
            if (textDictionary.ContainsKey(i))
            {
                textDictionary[i].SetActive(false);
                pool.Add(textDictionary[i]);
                textDictionary.Remove(i);
            }
        }

        oldMinIndex =minIndex;
        oldMaxIndex =maxIndex;
        
        for (int i = minIndex; i < maxIndex; i++)
        {

                if (textDictionary.ContainsKey(i) == false && pool.Count == 0 &&i<message.getMessage.Count)
                {


                    GameObject textObject = Instantiate(newText, content);
                    textObject.transform.localScale = Vector3.one;
                    textObject.transform.localPosition = new Vector2(220, -i * textHeight - 15);
                    textObject.GetComponent<Text>().text = message.getMessage[i];
                    textDictionary.Add(i, textObject);
                        
                    
                }
                else if(pool.Count>0&&!textDictionary.ContainsKey(i))
                {
                    pool[0].transform.localPosition = new Vector2(220, -i * textHeight - 15);
                    pool[0].SetActive(true);
                    pool[0].GetComponent<Text>().text=message.getMessage[i];
                    textDictionary.Add(i, pool[0]);
                    pool.RemoveAt(0);
                }
            
        }
    }
    public void onclick()
    {
        message.StringToData(inputText.text);
        inputText.text = null;
    }



}
